package com.wyt.common.socket.broad;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

@Component
public class InitHeartBroadListener implements ApplicationRunner {
    private static Logger logger = LoggerFactory.getLogger(InitHeartBroadListener.class);

    @Value("${heart.port}")
    private Integer heartPort;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        logger.info("============= 初始化心跳监听{} ===========",heartPort);
        new Thread(() -> {
            logger.info("监听线程启动");
            // 1.创建接受对象
            DatagramSocket socket = null;
            try {
                socket = new DatagramSocket(heartPort);
            } catch (SocketException e) {
                logger.error("创建监听对象异常:", e);
                return;
            }

            // 2.创建一个数据包接收数据
            byte[] buffer = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

            while (true) {
                try {
                    // 3.等待接受数据
                    socket.receive(packet);

                    // 4.取出数据
                    int len = packet.getLength();
                    String rs = new String(buffer, 0, len);
                    logger.info("收到来自节点[{}]消息,对方端口号为[{}],消息内容为[{}]", packet.getAddress(), packet.getPort(), rs);

                    // 5.更新或存储到数据库


                } catch (Exception e) {
                    logger.error("监听{}广播数据异常", heartPort,e);
                }
            }
        }).start();
        logger.info("============= 初始化心跳监听完毕 ===========");
    }
}
